// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

const {ccclass, property} = cc._decorator;


type imgtype = {
    url: string,
    plistUrl?: string
}

// 自定义一个动画播放
@ccclass
export default class MyAnimation extends cc.Component {
    // 播放速度
    @property(cc.Integer)
    playSpeed: number = 3;
    // 是否播放
    @property(Boolean)
    isPlay: boolean = false;

    // 图片数组
    imgArr: imgtype[] = []

    // LIFE-CYCLE CALLBACKS:

    // onLoad () {}
    hastime:number = 0;
    curIndex:number =  0;

    start () {
        this.imgArr.push({ url: 'bird1', plistUrl: 'birds/birdFly' });
        this.imgArr.push({ url: 'bird2', plistUrl: 'birds/birdFly' });
        this.imgArr.push({ url: 'bird3', plistUrl: 'birds/birdFly' });

        // this.changeImg(this.imgArr[this.curIndex++])
    }

    // 切换动画图片 
    changeImg(img: imgtype) {
        // 加载资源
        cc.resources.load(img.plistUrl, cc.SpriteAtlas,  (err, atlas)=> { 
            let sFrame = atlas.getSpriteFrame(img.url);
            this.node.getComponent(cc.Sprite).spriteFrame = sFrame;
        })
    }

    update (dt) {
        if (!this.isPlay) return;
        this.hastime += dt;
        if (this.hastime >= this.playSpeed) {
            this.changeImg(this.imgArr[this.curIndex])
            
            if (this.curIndex == this.imgArr.length - 1) {
                this.curIndex = 0;
            } else {
                this.curIndex++;
            }
            this.hastime = 0;
        }
    }
}
